/** 原生javascript扩展**/

/**
 * 去除字符串左右空格
 */
String.prototype.trim = function() {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

/**
 * 获取url的get参数
 * 
 * @param param
 *            要获取的参数名称，如果不传，则返回整个参数对象
 * @returns
 */
String.prototype.URLParams = function(param) {
	var params = {};
	var href = /^http/i.test(this) ? this: window.location.toString();
	var uri = href.split("?");
	if (!uri[1]) return null;

	uri = uri[1].split("#")[0];

	var paramSet = uri.split("&");
	var temp = [];
	for (index in paramSet) {
		temp = paramSet[index].split("=");
		params[temp[0]] = temp[1];
	}

	if (param) {
		if (params[param]) return params[param];
		else return null;
	} else {
		return params;
	}
};
/**
 * 字符串模版替换
 * 
 * @param this
 *            需要替换的字符串，例如：我是{{key1}}替换的字符串{{key2}}。
 * @param data
 *            替换的数据。json格式的数据或者数组。 eg： str：我是{{key1}}替换的字符串{{key2}}。
 *            data：{key1:"替换",key2:"替换2"}
 * 
 * str：我是{{0}}替换的字符串{{1}}。 data：["替换","替换2"]
 * @returns
 */
String.prototype.template = function(data) {
	var str = this;
	for (var key in data) {
		var value = data[key];
		if (value == null) value = "&nbsp;";
		str = str.replace(new RegExp("{{" + key + "}}", "gm"), value);
	}
	return str;
};
/**
 * 字符串替换所有匹配元素
 * 
 * @param old
 *            原元素
 * @param news
 *            替换元素
 * @returns
 */
String.prototype.replaceAll = function(old, news) {
	return this.replace(new RegExp(old, "gm"), news);
};

/**
 * 数组操作函数。去除数组中重复元素
 * 
 * @returns
 */
Array.prototype.unique = function() {
	var i, tmp = {};
	for (i = 0; i < this.length; i++) {
		if (typeof(tmp[this[i]]) == "undefined") tmp[this[i]] = 1;
	}
	this.length = 0;
	for (i in tmp) this[this.length] = i;
	return this;
};
/**
 * 数组操作函数。判断元素是否存在于数组中
 * 
 * @param value
 *            判断值
 * @returns {Number} 如果存在返回元素下标，不存在返回-1
 */
Array.prototype.contains = function(value) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == value) {
			return i;
		}
	}
	return - 1;
};
/**
 * 格式化时间
 * 
 * @param format
 * @returns
 */
Date.prototype.format = function(format) {
	if (!format) {
		format = "yyyy-MM-dd hh:mm:ss";
	}
	var o = {
			"M+": this.getMonth() + 1,
			// month
			"d+": this.getDate(),
			// day
			"h+": this.getHours(),
			// hour
			"m+": this.getMinutes(),
			// minute
			"s+": this.getSeconds(),
			// second
			"q+": Math.floor((this.getMonth() + 3) / 3),
			// quarter
			"S": this.getMilliseconds()
			// millisecond
	};

	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}

	for (var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
};

/** ****************************公共的js方法********************************* */
(function(){
	window.BN = {};
	BN.version = _VERSION_ || "0.0.0";
	/**
	 * 将JSON对象转换成字符串
	 * 
	 * @param o
	 * @returns
	 */
	BN.obj2str = function(o) {
		var r = [];
		if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
		if (typeof o == "object") {
			if (!o.sort) {
				for (var i in o) r.push("\""+i + "\":" + obj2str(o[i]));
				if ( !! document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
					r.push("toString:" + o.toString.toString());
				}
				r = "{" + r.join() + "}";
			} else {
				for (var i = 0; i < o.length; i++) r.push(obj2str(o[i]));
				r = "[" + r.join() + "]";
			}
			return r;
		}
		return o.toString();
	};

	BN.LOADEDMODULE=[];

	BN.loader = function(module) {
		if(BN.LOADEDMODULE.contains(module) !== -1){
			var m = eval(module);
			if(m && m.ready){
				m.ready.call();
			}
			return;
		}

		BN.LOADEDMODULE.push(module);

		var loaded = false;
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.language = "javascript";
		script.id = module.replaceAll("\\.", "-");
		script.src = _ROOT_ + "module/" + module.replaceAll("\\.", "/") + ".js?v="+BN.version;
		script.onload = script.onreadystatechange = function() {
			if (!loaded && (!script.readyState || script.readyState == "loaded" || script.readyState == "complete")) {
				loaded = true;
				script.onload = script.onreadystatechange = null;
				var m = eval(module);
				if(m && m.ready){
					m.ready.call();
				}
			}
		};
		document.getElementsByTagName("head")[0].appendChild(script);
	};

	BN.ns = function(path,cb) {
		var o = {}, d;
		d = path.split(".");
		o = window[d[0]] = window[d[0]] || {};
		for ( var k = 0; k < d.slice(1).length; k++) {
			o = o[d[k + 1]] = o[d[k + 1]] || {};
		}

		if(cb){
			cb.call(o);
		}
	};
})(window);


/** ****************************基于jQuery的扩展********************************* */
/**
 * form表单序列化成json对象
 */
jQuery.fn.formToJson = function() {
	var o = {};
	jQuery.each(jQuery(this).serializeArray(),
			function(index) {
		if (o[this['name']]) {
			o[this['name']] = o[this['name']] + "," + this['value'];
		} else {
			o[this['name']] = this['value'];
		}
	});
	return o;
};

BN.ns("beny.common",function(){
	this.statusCodeMessageer = {
			404 : function() {
				jQuery.messager.alert('错误404', '访问页面不存在！');
			},
			500:function() {
				var response = jQuery.parseJSON(this.responseText);
				jQuery.messager.alert(this.statusText, response.message);
			}
	};
});

jQuery.ajaxSetup({
	type: 'POST',
	error:function(jqXHR, textStatus, errorThrown){
		var statusCode = jqXHR.status;
		if(beny.common.statusCodeMessageer[statusCode]){
			beny.common.statusCodeMessageer[statusCode].call(jqXHR);
		}
	}
});

jQuery("html").ajaxStart(function() {
	top.jQuery.messager.progress({
		text: '加载中....',
		interval: 100
	});
});

jQuery("html").ajaxStop(function() {
	if (top.jQuery("body>div.messager-window>div.messager-body>div.messager-progress").length) {
		setTimeout(function(){
			var msg = top.jQuery("body>div.messager-window>div.messager-body>div.messager-progress").parent();
			if (msg[0].timer) {
				clearInterval(msg[0].timer);
			}
			msg.window("close");
		},500);
	}
});


/******************************基于jQueryEasyui的扩展**********************************/

/**
 * 覆盖panel默认的extractor
 */
jQuery.extend(jQuery.fn.panel.defaults,{
	extractor:function(data){
		var reg=/<body[^>]*>((.|[\n\r])*)<\/body>/im;
		var content=reg.exec(data);
		if(content){
			data =  content[1];
		}
		reg = /<body.*md=[\",']([^\s>,^\",^']+)[\",']/im;
		var md = reg.exec(content[0]);
		if(md && md[1]){
			BN.loader(md[1]);
		}
		md = null;
		reg = null;
		return data; 
	}
});

(function ($) {
	function S4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}
	function CreateIndentityWindowId() {
		return "UUID-" + (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	}
	function destroy(target) {
		$(target).dialog("destroy");
	}
	function getWindow(target) {
		if (typeof target == "string") {
			return document.getElementById(target);
		} else {
			return $(target).closest(".window-body");
		}
	}
	
	if(window.top != self){
		if(window.top.jQuery && window.top.jQuery.window){
			$.window = window.top.jQuery.window;
			return;
		}
		throw "父窗口没有导入jQuery或定义window插件！";
	}
	
	$.window = function (options) {
		if (!options.url && !options.contents) {
			$.messager.alert("提示", "缺少必要参数!(url or contents)");
			return false;
		}
		var windowId = CreateIndentityWindowId();
		if (options.winId) {
			windowId = options.winId;
		} else {
			options.winId = windowId;
		}
		var defaultBtn = [{
			text : '关闭',
			handler : function () {
				$("#" + windowId).dialog("close");
			}
		}
		];
		if(options.buttons){
			options.buttons = $.merge(options.buttons || [], defaultBtn);
		}
		options = $.extend({}, $.window.defaults, options || {});
		if (options.isMax) {
			options.draggable = false;
			options.closed = true;
		}
		var dialog = $('<div/>');
		if (options.target != 'body') {
			options.inline = true;
		}
		dialog.appendTo($(options.target));
		dialog.dialog($.extend({}, options, {
			onClose : function () {
				if (typeof options.onClose == "function") {
					options.onClose.call(dialog,$);
				}
				destroy(this);
			},
			onMove : function (left, top) {
				if (typeof options.onMove == "function") {
					options.onMove.call(dialog,$);
				}
				var o = $.data(this, 'panel').options;
				if (top < 0) {
					$(this).dialog("move", {
						"left" : left,
						"top" : 0
					});
				} else if (o.maximized) {
					$(this).dialog("restore");
					$(this).dialog("move", {
						"left" : left + 100,
						"top" : top
					});
				}
				if (top > ($(o.target).height() - 20)) {
					$(this).dialog("move", {
						"left" : left,
						"top" : ($(o.target).height() - 25)
					});
				}
			}
		}));
		if (options.align) {
			var w = dialog.closest(".window");
			switch (options.align) {
			case "right":
				dialog.dialog("move", {
					left : w.parent().width() - w.width() - 10
				});
				break;
			case "tright":
				dialog.dialog("move", {
					left : w.parent().width() - w.width() - 10,
					top : 0
				});
				break;
			case "bright":
				dialog.dialog("move", {
					left : w.parent().width() - w.width() - 10,
					top : w.parent().height() - w.height() - 10
				});
				break;
			case "left":
				dialog.dialog("move", {
					left : 0
				});
				break;
			case "tleft":
				dialog.dialog("move", {
					left : 0,
					top : 0
				});
				break;
			case "bleft":
				dialog.dialog("move", {
					left : 0,
					top : w.parent().height() - w.height() - 10
				});
				break;
			case "top":
				dialog.dialog("move", {
					top : 0
				});
				break;
			case "bottom":
				dialog.dialog("move", {
					top : w.parent().height() - w.height() - 10
				});
				break;
			}
		}
		if (options.isMax) {
			dialog.dialog("maximize");
			dialog.dialog("open");
		}
	
		if (options.contents) {
			ajaxSuccess(options.contents);
		} else {
			if (!options.isIframe) {
				$.ajax({
					url : options.url,
					type : options.ajaxType || "POST",
					data : options.data == null ? "" : options.data,
					success : function (date) {
						ajaxSuccess(date);
					}
				});
			} else {
				ajaxSuccess();
			}
		}
		dialog.attr("id",windowId);
		
		dialog.destroy = function(){
			destroy(this);
		};
		
		return dialog;
		function ajaxSuccess(date) {
			if (options.isIframe && !date) {
				dialog.find("div.dialog-content").html('<iframe width="100%" height="100%" frameborder="0" src="' + options.url + '" ></iframe>');
			} else {
				dialog.find("div.dialog-content").html(date);
			}
			$.parser.parse(dialog);
			options.onComplete.call(dialog,$);
		}
	};
	
	$.window.defaults = $.extend({}, $.fn.dialog.defaults, {
		url : '',
		data : '',
		contents:'',
		ajaxType:"POST",
		target : 'body',
		height : 200,
		width : 400,
		collapsible : false,
		minimizable : false,
		maximizable : false,
		closable : true,
		modal : true,
		shadow : false,
		onComplete : function (topjQuery) {}
	});
})(jQuery);